<?php
/**
 * 订单管理模型
 * User: John
 * Date: 17-1-3
 * Time: 上午11:18
 */

namespace app\backend\model;

use think\Model;

class BillManager extends Model
{
    private $payBillTable     = 'z_pay_bill';
    private $leaseExtTable    = 'z_contract_order_ext';
    private $payComment       = 'z_pay_bill_comment';
    private $trustBillTable   = 'z_trust_bill';
    private $memberTable      = 'z_member';
    private $settleRuleTable  = 'z_settle_rule';
    private $alipayTable      = 'z_alipay';
    private $manualCollection = 'z_manual_collection';
    private $_insertLimit     = 1000;

    public function __construct() {
        parent::__construct();
    }

    /**
     * 获取租赁账单
     * @date   2017-1-16
     * @author wuhao
     *
     * @param  int     $memberId     用户id
     * @param  int     $pdtype       父账号类型
     * @param  int     $dtype        子账号类型
     * @param  string  $beginMonth   查询开始时间
     * @param  string  $endMonth     查询结束时间
     * @param  string  $status       应付订单状态 0=未支付 1=已支付 为空的话不限制
     * @param  int     $buildingId   楼宇id
     * @param  string  $room         房号
     * @param  array   $houseId      员工限制房源
     * @param  int     $page         页数
     * @param  int     $pageSize     每页个数
     *
     * @return array|bool
     */
    public function leaseBill($memberId, $pdtype, $dtype, $beginMonth = '', $endMonth = '', $status = '', $buildingId, $room = '', $houseId = [],  $page = 1, $pageSize = 15)
    {
        if (!$memberId) {
            return false;
        }
        $where = [];
        if ($pdtype == 2) { //租户
            $where['p.tenant_id']  = $memberId;
            $field = 'p.ordernum contract_id, p.tenant_id, p.status, p.begin_cycle, p.end_cycle, sum(p.money) total_money';
            $group = 'p.tenant_id, p.ordernum, p.begin_cycle, p.end_cycle, p.status';
        } else {
            $where['p.owner_id']   = $memberId;
            $field = 'p.ordernum contract_id, p.owner_id, p.status, p.begin_cycle,p. end_cycle, sum(p.money) total_money';
            $group = 'p.owner_id, p.ordernum,p.begin_cycle, p.end_cycle, p.status';
        }

        if ($dtype == 7) { //子员工限制房源
            if ($houseId) {
                $where['e.house_id'] = ['in', $houseId];
//                $ordernumArr = $this->table($this->leaseExtTable)->field('ordernum')->where(['house_id' => ['in', $houseId],'status'=>1])->select();
//                $ordernumArr = array_column($ordernumArr, 'ordernum');
//                $map['p.ordernum'] = ['in', $ordernumArr];
            } else {
                return [];
            }
        }

        if ($room) {
            $where['e.room'] = $room;
//            $ordernum = $this->table($this->leaseExtTable)->field('ordernum')->where(['room' => $room, 'status' =>1])->find();
//            if (!$ordernum) {
//                return [];
//            } else {
//                $where['p.ordernum'] = $ordernum['ordernum'];
//            }
        }
        if ($buildingId) {
            $where['p.building_id'] = $buildingId;
        }


        if ($beginMonth && $endMonth && strtotime($beginMonth) && strtotime($endMonth)) {
            $where['p.begin_cycle'] = ['between', [$beginMonth, $endMonth]];
        } elseif ($endMonth  && strtotime($endMonth)) {
            $where['p.begin_cycle'] = ['elt', $endMonth];
        } elseif ($beginMonth  && strtotime($beginMonth)) {
            $where['p.begin_cycle'] = ['elt', $beginMonth];
        }

        if (is_numeric($status)) {
            $where['p.status']     = $status;
        }

        $where['p.is_delete']   = 0;
        $where['e.status']      = 1;
        $res   = $this->setTable($this->payBillTable.' p')->join( $this->leaseExtTable .' e' ,'e.ordernum=p.ordernum','LEFT')->field($field)
            ->where($where)->group($group)->order('e.room')->page($page, $pageSize)->select();
        return $res;
    }

    /**
     * 获取租赁账单总数
     * @date   2017-1-16
     * @author wuhao
     *
     * @param  int     $memberId     用户id
     * @param  int     $dtype        用户类型
     * @param  string  $beginMonth   查询开始时间
     * @param  string  $endMonth     查询结束时间
     * @param  string  $status       应付订单状态 0=未支付 1=已支付 为空的话不限制
     * @param  int     $buildingId   楼宇Id
     * @param  string  $room         房号
     * @param  array   $houseId      员工限制房源
     *
     * @return array|bool
     */
    public function countLeaseBill($memberId, $pdtype, $dtype, $beginMonth = '', $endMonth = '', $status = '', $buildingId, $room = '', $houseId = [])
    {
        if (!$memberId) {
            return false;
        }
        $where = [];
        if ($pdtype == 2) { //租户
            $where['p.tenant_id']  = $memberId;
            $content = 'distinct p.tenant_id, p.ordernum, p.begin_cycle, p.end_cycle, p.status';
        } else {
            $where['p.owner_id']   = $memberId;
            $content = 'distinct p.owner_id, p.ordernum, p.begin_cycle, p.end_cycle, p.status';
        }

        if ($dtype == 7) { //子员工限制房源
            if ($houseId) {
                $where['e.house_id'] = ['in', $houseId];
//                $ordernumArr = $this->table($this->leaseExtTable)->field('ordernum')->where(['house_id' => ['in', $houseId],'status'=>1])->select();
//                $ordernumArr = array_column($ordernumArr, 'ordernum');
//                $map['p.ordernum'] = ['in', $ordernumArr];
            } else {
                return [];
            }
        }

        if ($room) {
            $where['e.room'] = $room;
//            $ordernum = $this->table($this->leaseExtTable)->field('ordernum')->where(['room' => $room, 'status' =>1])->find();
//            if (!$ordernum) {
//                return [];
//            } else {
//                $where['p.ordernum'] = $ordernum['ordernum'];
//            }
        }
        if ($buildingId) {
            $where['p.building_id'] = $buildingId;
        }


        if ($beginMonth && $endMonth && strtotime($beginMonth) && strtotime($endMonth)) {
            $where['p.begin_cycle'] = ['between', [$beginMonth, $endMonth]];
        } elseif ($endMonth  && strtotime($endMonth)) {
            $where['p.begin_cycle'] = ['elt', $endMonth];
        } elseif ($beginMonth  && strtotime($beginMonth)) {
            $where['p.begin_cycle'] = ['elt', $beginMonth];
        }

        if (is_numeric($status)) {
            $where['p.status']     = $status;
        }
        $where['p.is_delete']   = 0;
        $where['e.status']      = 1;

        $res =  $this->setTable($this->payBillTable.' p')
            ->join( $this->leaseExtTable .' e' ,'e.ordernum=p.ordernum','LEFT')
            ->where($where)
            ->count($content);

        return $res;
    }

    /**
     * 查看租户账单明细
     * @date   2017-02-06
     * @author wuhao
     *
     * @param  string  $orderNum    合同编号
     * @param  string  $beginCycle  周期开始
     * @param  string  $endCycle    周期结束
     *
     * @return array|bool
     */
    public function leaseBillDetail($orderNum, $beginCycle, $endCycle)
    {
        if (!$orderNum  || !$beginCycle || !$endCycle) {
            return false;
        }

        $where = ['ordernum' => $orderNum, 'begin_cycle' => $beginCycle, 'end_cycle' => $endCycle, 'is_delete' => 0];
        $field = 'id, owner_id, free_money, money, type_money, tenant_id, bill_name, begin_cycle, end_cycle';
        return $this->setTable($this->payBillTable)->field($field)->where($where)->select();
    }

    /**
     * 获取租赁账单信息
     * @date   2017-01-17
     * @author wuhao
     *
     * @param  array   $where     条件
     * @param  string  $field     获取字段
     *
     * @return array
     */
    public function getPayBillInfo($where, $field = '*')
    {
        return $this->setTable($this->payBillTable)->field($field)->where($where)->select();
    }

    /**
     * 根据订单号获取租赁账单
     * @date   2017-01-16
     * @author Lanlc
     *
     * @param  mix      $order  订单号
     * @param  string   $field  获取字段信息
     * @param  array    $map    额外查询条件
     *
     * @return array
     */
    public function getPayBillByOrderNum($order, $field, $map)
    {
        if ($map) {
            $where = $map;
        }
        if (is_array($order)) {
            $where['ordernum'] = ['IN', $order];
        } else {
            $where['ordernum'] = $order;
        }
        $where['is_delete']   = 0;
        return $this->setTable($this->payBillTable)->field($field)->where($where)->select();
    }

    /**
     * 根据订单号获取租赁账单总额
     * @date   2017-01-16
     * @author Lanlc
     *
     * @param  mix      $order  订单号
     * @param  array    $map    额外查询条件
     *
     * @return array|bool
     */
    public function getPayBillCntByOrderNum($order, $map)
    {
        if ($map) {
            $where = $map;
        }
        $where['ordernum'] = $order;
        $where['is_delete']   = 0;
        $res = $this->setTable($this->payBillTable)->field('sum(money) as money')->where($where)->find();
        if ($res) {
            return $res['money'];
        } else {
            return false;
        }
    }

    /**
     * 更新租赁账单信息
     * @date   2017-01-20
     * @author Lanlc
     *
     * @param  array  $where  更新条件
     * @param  array  $data   更新数据
     *
     * @return
     */
    public function updatePayBill($where, $data)
    {
        return $this->setTable($this->payBillTable)->where($where)->update($data);
    }

    /**
     * 更新租赁账单信息
     * @date   2017-01-20
     * @author Lanlc
     *
     * @param  array  $where  更新条件
     * @param  array  $data   更新数据
     *
     * @return bool
     */
    public function updateTrustBill($where, $data)
    {
        return $this->setTable($this->trustBillTable)->where($where)->update($data);
    }

    /**
     * 根据托管订单获取出租率对应的分成比例
     * @date   2017-01-23
     * @author Lanlc
     *
     * @param  string  $settleNum  托管订单
     * @param  int     $rent       出租率
     *
     * @return array
     */
    public function getShareData($settleNum, $rent)
    {
        return $this->setTable($this->settleRuleTable)->field('*')->where(['settlenum' => $settleNum, 'rental_rate' => ['ELT', $rent]])
            ->order('split_ratio', 'desc')->find();
    }

    /**
     * 获取已经付款的房租的账单总数
     * @date   2017-01-23
     * @author Lanlc
     *
     * @param  int  $buildingId  楼宇ID
     * @param  string  $status      结算状态
     * @param  int  $billMonth   账单月份
     * @param  int  $typeMoney   账单金额类型
     * @param  array  $houseId   房源编号数组
     *
     * @return array|bool
     */
    public function getPayedBill($buildingId, $status='', $billMonth, $typeMoney=0, array $houseId = [])
    {
        if (!$billMonth || !$buildingId ||!$houseId) {
            return false;
        }
        $field = 'id,money';
        $where = ['building_id' => $buildingId, 'bill_time' => $billMonth];
        if ($typeMoney) {
            $where['type_money'] = 1;
        }
        if ($status !== '') {
            $where['status'] = $status;
        }
        if ($houseId) {
            $where['house_id'] = ['in', $houseId];
        }
        $where['is_delete']   = 0;
        $res = $this->setTable($this->payBillTable)->field($field)->where($where)->select();
        return $res ? $res : [];
    }

    /**
     * 保存托管订单
     * @date   2017-01-23
     * @author Lanlc
     *
     * @param  array  $data  待保存的数据
     *
     * @return int
     */
    public function insetTrustBill($data)
    {
        if (count($data) > $this->_insertLimit) {
            $insertData = [];
            foreach ($data as $k => $v) {
                $insertData[] = $v;
                if (count($insertData) == $this->_insertLimit) {
                    $this->setTable($this->trustBillTable)->insertAll($insertData);
                    $insertData = [];
                }
            }
            //将没有插入的数据最后插入
            if ($insertData) {
                $this->setTable($this->trustBillTable)->insertAll($insertData);
            }
        } else {
            $this->setTable($this->trustBillTable)->insertAll($data);
        }
    }

    /**
     * 获取应收房租的总额
     * @date   2017-01-23
     * @author Lanlc
     *
     * @param  int  $buildingId  楼宇ID
     * @param  int  $billMonth   账单月份
     * @param  int  $typeMoney   金额类型
     *
     * @return array
     */
    public function getRentedCntMoney($tempHouseIds, $billMonth, $typeMoney=0)
    {
        $field = 'sum(money) as sum';
        $where = ['house_id' => ['IN', $tempHouseIds], 'bill_time' => $billMonth];
        if ($typeMoney) {
            $where['type_money'] = 1;
        }
        $where['is_delete']   = 0;
        $res = $this->setTable($this->payBillTable)->field($field)->where($where)->find();
        return $res ? $res : [];
    }

    /**
     * 获取托管公司应付账单
     * @date   2017-1-24
     * @author wuhao
     *
     * @param  int     $memberId     用户id
     * @param  int     $dtype        用户类型
     * @param  string  $beginMonth   查询开始时间
     * @param  string  $endMonth     查询结束时间
     * @param  string  $name         业主名称
     * @param  string  $mobile       业主电话
     * @param  string  $status       应付订单状态 0=未支付 1=已支付 为空的话不限制
     * @param  int     $page         页数
     * @param  int     $pageSize     每页个数
     *
     * @return array|bool
     */
    public function getTrustPayBill($memberId, $dtype, $beginMonth = '', $endMonth = '', $name = '', $mobile = '', $status = '', $page = 1, $pageSize = 15)
    {
        if (!$memberId || !in_array($dtype, [3, 4])) {
            return false;
        }

        $where['t.tenant_id'] = $memberId;

        if (is_numeric($status)) {
            $where['t.status']    = $status;
        }
        if ($mobile) {
            $where['m.mobile'] = $mobile;
        }
        if ($beginMonth && $endMonth) {
            $where['t.begin_cycle'] = [['egt', $beginMonth], ['lt', $endMonth]];
        } else {
            $where['t.begin_cycle'] = ['elt', $endMonth];
        }
        $where['t.is_delete']    = 0;
        if ($name) {
            $where['m.nickname'] = ['like', "%$name%"];
        }

        $field = 'm.nickname, m.mobile, t.ordernum,t.owner_id, t.tenant_id, t.bill_time, t.begin_cycle, t.end_cycle, t.ratio,
         t.status, t.building_id,t.should_rent,t.share_money';
        $join = [
            [$this->memberTable.' m', 'm.id=t.owner_id', 'LEFT'],
        ];

        $res =  $this->setTable($this->trustBillTable.' t')->field($field)->join($join)->where($where)->page($page, $pageSize)->select();
        if (!$res) {
            return [];
        }
        $sum = $this->setTable($this->trustBillTable.' t')->field($field)->join($join)->where($where)->page($page, $pageSize)->count();
        $data = [
            'list'         => $res,
            'current_page' => $page,
            'total'        => ceil($sum / $pageSize),
        ];
        return $data;
    }

    /**
     * 获取应收托管公司账单
     * @date   2017-1-24
     * @author wuhao
     *
     * @param  int     $memberId     用户id
     * @param  int     $dtype        用户类型
     * @param  string  $beginMonth   查询开始时间
     * @param  string  $endMonth     查询结束时间
     * @param  string  $status       应付订单状态 0=未支付 1=已支付 为空的话不限制
     * @param  int     $page         页数
     * @param  int     $pageSize     每页个数
     *
     * @return array|bool
     */
    public function getTrustIncomeBill($memberId, $dtype, $name, $mobile, $beginMonth = '', $endMonth = '', $status = '', $page = 1, $pageSize = 15)
    {
        if (!$memberId || !in_array($dtype, [1, 3, 4])) {
            return false;
        }
        $where = [];
        $where['t.owner_id'] = $memberId;

        if (is_numeric($status)) {
            $where['t.status']    = $status;
        }
        if ($beginMonth && $endMonth) {
            $where['t.begin_cycle'] = [['egt', $beginMonth], ['lt', $endMonth]];
        } else {
            $where['t.begin_cycle'] = ['elt', $endMonth];
        }
        if ($mobile) {
            $where['m.mobile'] = $mobile;
        }
        $where['t.is_delete']    = 0;
        if ($name) {
            $where['m.nickname'] = ['like',"%$name%"];
        }

        $field = 'm.nickname, m.mobile, t.ordernum, t.owner_id, t.tenant_id, t.bill_time, t.begin_cycle, t.end_cycle,t.ratio,
         t.status, t.building_id, t.should_rent, t.real_rent, t.share_money';
        $join  = [
            [$this->memberTable.' m', 'm.id=t.tenant_id', 'LEFT'],
        ];
        $res =  $this->setTable($this->trustBillTable.' t')->field($field)->join($join)->where($where)->page($page, $pageSize)->select();
        if (!$res) {
            return [];
        }
        $sum = $this->setTable($this->trustBillTable.' t')->field($field)->join($join)->where($where)->page($page, $pageSize)->count();

        $data = [
            'list'         => $res,
            'current_page' => $page,
            'total'        => ceil($sum / $pageSize),
        ];
        return $data;
    }

    /**
     * 托管缴费页面--获取总金额
     * @date   2017-01-24
     * @author wuhao
     *
     * @param  string  $id        合同编号
     * @param  int     $memberId  应付人id
     * @param  int     $dtype     登陆者类型
     *
     * @return array
     */
    public function trustPayTotal($id, $memberId, $dtype, $beginCycle, $endCycle, $status)
    {
        if ($dtype == 3) {
            $where = [
                'ordernum'    => $id,
                'tenant_id'   => $memberId,
                'begin_cycle' => $beginCycle,
                'end_cycle'   => $endCycle,
                'status'      => $status,
                'is_delete' => 0
            ];
        } else {
            $where = [
                'ordernum'    => $id,
                'begin_cycle' => $beginCycle,
                'end_cycle'   => $endCycle,
                'status'      => $status,
                'is_delete' => 0
            ];
        }

        $field = 'begin_cycle, end_cycle, tenant_id, should_rent, share_money';
        return $this->setTable($this->trustBillTable)->field($field)->where($where)->find();
    }

    /**
     * 新增水电，公摊水电账单
     * @date   2017-02-06
     * @author wuhao
     *
     * @param string $ordernum   合同编号
     * @param int    $buildingId 楼宇id
     * @param int    $chargeOut  出账日期20170505
     * @param int    $type       账单周期类型 1月, 2季度, 3半年, 4年
     * @param int    $beginCycle 开始周期 20170505
     * @param int    $endCycle   结束周期 20170505
     * @param int    $ownerId    收款人id
     * @param int    $tenantId   租户id
     * @param int    $money      金额分
     * @param int    $typeMoney  1房租，2物业，3水，4电, 5公摊水，6公摊电, 7税费, 8其他费用,9优惠金额
     * @param int    $billTime   账单月份或年份
     * @param string $billName   账单名称
     * @return int
     */
    public function addPayBill($ordernum, $buildingId, $chargeOut, $type, $beginCycle, $endCycle, $ownerId, $tenantId, $money, $typeMoney, $billTime, $billName)
    {
        $data = [
            'ordernum'    => $ordernum,
            'building_id' => $buildingId,
            'charge_out'  => $chargeOut,
            'type'        => $type,
            'begin_cycle' => $beginCycle,
            'end_cycle'   => $endCycle,
            'owner_id'    => $ownerId,
            'tenant_id'   => $tenantId,
            'money'       => $money,
            'status'      => 0,
            'type_money'  => $typeMoney,
            'time'        => time(),
            'bill_time'   => $billTime,
            'bill_name'   => $billName,
        ];
        return $this->setTable($this->payBillTable)->insertGetId($data);
    }


    /**
     * 查询在线支付记录数据
     * @date   2017-02-08
     * @author Lanlc
     *
     * @param  string  $field  查询字段
     * @param  array   $where  查询条件
     *
     * @return array
     */
    public function getAliPayRec($field = '*', $where)
    {
        return $this->setTable($this->alipayTable)->field($field)->where($where)->select();
    }
    /**
     * 获取托管账单支付状态
     * @date   2017-02-08
     * @author wuhao
     *
     * @param  string  $orderNum         订单号
     * @param  int     $beginCycle       账单开始时间
     * @param  int     $endCycle         账单结束时间
     * @return array
     */
    public function trustBillStatus($orderNum, $beginCycle, $endCycle)
    {
        $where = [
            'ordernum'    => $orderNum,
            'begin_cycle' => $beginCycle,
            'end_cycle'   => $endCycle,
            'is_delete'   => 0,
        ];
        $field = 'status';
        return $this->setTable($this->trustBillTable)->field($field)->where($where)->find();
    }

    /**
     * 获取租赁账单支付状态
     * @date   2017-02-08
     * @author wuhao
     *
     * @param  string  $orderNum   订单号
     * @param  int     $beginCycle 账单开始时间
     * @param  int     $endCycle   账单结束时间
     * @return array
     */
    public function payBillStatus($orderNum, $beginCycle, $endCycle)
    {
        $where = [
            'ordernum'    => $orderNum,
            'begin_cycle' => $beginCycle,
            'end_cycle'   => $endCycle,
            'is_delete'   => 0,
        ];
        $field = 'status';
        return $this->setTable($this->payBillTable)->field($field)->where($where)->find();
    }

    /**
     * 获取租赁账单
     * @date   2017-03-23
     * @author wuhao
     *
     * @param  array    $where   条件
     * @param  string   $field   字段
     * @param  int      $page    页数
     * @param  int      $pageSize 每页个数
     * @return array
     */
    public function getPayBill($where, $field = '*', $page = 1, $pageSize = 10)
    {
        return $this->setTable($this->payBillTable)->field($field)->where($where)->page($page, $pageSize)->select();
    }

    /**
     * 获取租赁账单
     * @date   2017-03-23
     * @author wuhao
     *
     * @param  array    $where   条件
     * @param  string   $field   字段
     * @return array
     */
    public function getPayBillList($where, $field = '*')
    {
        return $this->setTable($this->payBillTable)->field($field)->where($where)->select();
    }

    /**
     * 获取租赁账单的租户信息
     * @date   2017-03-23
     * @author wuhao
     *
     * @param  string   $ordernum   合同编号
     * @return array
     */
    public function getPayBillTenant($ordernum)
    {
        return $this->setTable($this->payBillTable)->field('tenant_id')->where(['ordernum' => $ordernum])->limit(1)->find();
    }

    /**
     * 获取托管订单
     * @date   2017-01-23
     * @author Lanlc
     *
     * @param  array   $where     查询条件
     * @param  string  $field     查询字段
     * @param  int     $offSet    偏移量
     * @param  int     $pageSize  数量
     *
     * @return array
     */
    public function getTrustBill($where, $field, $offSet=0, $pageSize=10)
    {
        return $this->setTable($this->trustBillTable)->field($field)->where($where)->limit($offSet, $pageSize)->select();
    }

    /**
     * 获取托管订单总数
     * @date   2017-01-23
     * @author Lanlc
     *
     * @param  array   $where     查询条件
     * @param  string  $field     查询字段
     *
     * @return array
     */
    public function cntTrustBill($where, $field)
    {
        return $this->setTable($this->trustBillTable)->field($field)->where($where)->count();
    }

    /**
     * 获取所有的托管订单
     * @date   2017-01-23
     * @author Lanlc
     *
     * @param  array   $where     查询条件
     * @param  string  $field     查询字段
     *
     * @return array

     */
    public function getAllTrustBill($where, $field)
    {
        return $this->setTable($this->trustBillTable)->field($field)->where($where)->select();
    }

    /**
     * 租赁账单生成
     * @date   2017-04-12
     * @author wuhao
     *
     * @param  array   $data     数据
     *
     * @return array|bool
     */
    public function insertPayBill($data)
    {
        if (!$data || !is_array($data)) {
            return false;
        }
        return $this->setTable($this->payBillTable)->insertAll($data);
    }

    /**
     * 租赁账单生成
     * @date   2017-04-12
     * @author wuhao
     *
     * @param  int   $ordernum   订单id
     *
     * @return array|bool
     */
    public function getTrustBillByOrdernum($ordernum)
    {
        if (!$ordernum) {
            return false;
        }
        $where = ['ordernum' => $ordernum];
        $this->setTable($this->trustBillTable)->where($where)->select();
    }

    /**
     * 获取租赁账单的备注
     * @date   2017-05-18
     * @author wuhao
     *
     * @param  int   $ordernum   订单id
     * @param  int   $beginCycle 周期开始
     * @param  int   $endCycle   周期结束
     *
     * @return array|bool
     */
    public function getPayBillComment($ordernum, $beginCycle, $endCycle)
    {
        if (!$ordernum || !$beginCycle || !$endCycle) {
            return false;
        }
        $where = ['ordernum' => $ordernum, 'begin_cycle' => $beginCycle, 'end_cycle' => $endCycle];
        $field = 'comment';
        $res = $this->setTable($this->payComment)->field($field)->where($where)->select();
        return $res ?: [];
    }

    /**
     * 新增租赁账单的备注
     * @date   2017-05-18
     * @author wuhao
     *
     * @param  int   $ordernum   订单id
     * @param  int   $beginCycle 周期开始
     * @param  int   $endCycle   周期结束
     * @param  string $comment   备注
     * @param  int   $memberId   添加人id
     *
     * @return array|bool
     */
    public function addPayBillComment($ordernum, $beginCycle, $endCycle, $comment, $memberId)
    {
        if (!$ordernum || !$beginCycle || !$endCycle ||!$comment || !$memberId) {
            return false;
        }
        $data = [
            'ordernum'    => $ordernum,
            'begin_cycle' => $beginCycle,
            'end_cycle'   => $endCycle,
            'comment'     => $comment,
            'create_user' => $memberId,
            'create_time' => time(),
        ];
        $res = $this->setTable($this->payComment)->insertGetId($data);
        return $res ?: false;
    }

    /**
     * 收入管理-获取收入列表
     * @date   2017-05-18
     * @author wuhao
     *
     * @param  int   $memberId   收款人id
     * @param  int   $billTime   账单月 201705
     * @param  int   $buildingId 楼宇id
     * @param  bool  $usePagination 是否分页
     * @param  int   $page       页数
     * @param  int   $pageSize   每页个数
     *
     * @return bool|array
     */
    public function getLeaseIncomeBill($memberId, $billTime, $buildingId, $usePagination = false, $page = 1, $pageSize = 15)
    {
        if (!$memberId || !$billTime) {
            return false;
        }

        $where['owner_id'] = $memberId;
        $where['bill_time'] = $billTime;
        $where['is_delete'] = 0;
        if ($buildingId) {
            $where['building_id'] = $buildingId;
        }
        $field = 'owner_id, ordernum, begin_cycle, end_cycle, status, building_id,  charge_out, tenant_id, SUM(money) as money';
        //$where = ['owner_id' => $memberId, 'bill_time' => $billTime, 'is_delete' =>0];
        $group = 'owner_id, ordernum,begin_cycle, end_cycle, status';
        if ($usePagination == false) {
            $res = $this->setTable($this->payBillTable)->field($field)->where($where)->group($group)->select();
            $data = ['list' => $res];
            return $data;
        } else {
            $res = $this->setTable($this->payBillTable)->field($field)->where($where)->group($group)->page($page, $pageSize)->select();

            if (!$res) {
                return [];
            } else {
                $field2= 'distinct owner_id, ordernum,begin_cycle, end_cycle, status';
                $sum = $this->setTable($this->payBillTable)->where($where)->count($field2);
                $total = ceil($sum / $pageSize);
                $data = [
                    'list'         => $res,
                    'current_page' => $page,
                    'total'        => $total,
                ];
                return $data;
            }
        }
    }

    /**
     * 租赁账单 --获取收款人或付款人的某个账单的详情
     * @date   2017-05-18
     * @author wuhao
     *
     * @param  int     $ownerId     收款人或付款人id
     * @param  int     $dtype       用户类型
     * @param  string  $ordernum    合同编号
     * @param  int     $beginCycle  账单开始周期
     * @param  int     $endCycle    账单结束周期
     * @param  string  $status      结算状态 0=没结算 1=已结算 为空不限制
     * @param  string  $field       要获取的字段
     * @return bool|array
     */
    public function getBillDetailByOwner($ownerId, $dtype, $ordernum, $beginCycle, $endCycle, $status = '', $field = '*')
    {
        if (!$ownerId || !$ordernum || !$beginCycle || !$endCycle || !in_array($dtype, [1, 2, 3, 4, 5, 6])) {
            return false;
        }
        $where['ordernum'] = $ordernum;
        if ($dtype != 2) {
            $where['owner_id'] = $ownerId;
        } else {
            $where['tenant_id'] = $ownerId;
        }

        $where['begin_cycle'] = $beginCycle;
        $where['end_cycle'] = $endCycle;
        if (in_array($status, [0 ,1])) {
            $where['status'] = $status;
        }
        $where['is_delete'] = 0;
        return $this->setTable($this->payBillTable)->field($field)->where($where)->select();
    }

    /**
     * 租赁账单新增人工确认收款记录
     * @date   2017-05-18
     * @author wuhao
     *
     * @param  array     $orderIdArr   租赁账单id数组
     * @param  int       $payType      支付类型
     * @param  string    $serialNumber 流水号
     * @param  int       $payTime      支付时间
     * @param  int       $ownerId      应收人id
     *
     * @return array
     */
    public function addManualCollectionRecord($orderIdArr, $payType, $serialNumber, $payTime, $ownerId)
    {
        if (!$orderIdArr || !$payTime ||  !is_array($orderIdArr) || !$ownerId) {
            return ['code' => 400, 'msg' => '参数有误'];
        }

        //获取所给的账单id对应的详情
        $billDetail = $this->getPayBillList(['id' => ['in', $orderIdArr], 'status' => 0, 'is_delete' => 0], 'id, ordernum, money, type_money, tenant_id');
        if (!$billDetail) {
            return ['code' => 400, 'msg' => '找不到对应账单'];
        }
        $insertData = [];

        foreach ($billDetail as $b) {
            $insertData[] = [
                'ordernum'      => $b['ordernum'],
                'order_id'      => $b['id'],
                'money'         => $b['money'],
                'type_money'    => $b['type_money'],
                'owner_id'      => $ownerId,
                'tenant_id'     => $b['tenant_id'],
                'pay_type'      => $payType,
                'serial_number' => $serialNumber,
                'pay_time'      => $payTime,
                'create_time'   => date('Y-m-d H:i:s'),
            ];
        }
        //开始事务
        $this->startTrans();
        //更新账单状态
        $res1 = $this->updatePayBill(['id' => ['in', $orderIdArr]], ['status' => 1, 'pay_time'=>date('Y-m-d H:i:s', strtotime($payTime))]);
        if (!$res1) {
            $this->rollback();
            return ['code' => 201, 'msg' => $this->getLastSql()];
        }
        //插入人工收款列表
        $res2 = $this->setTable($this->manualCollection)->insertAll($insertData);
        if (!$res2) {
            $this->rollback();
            return ['code' => 202, 'msg' => $this->getLastSql()];
        }

        $this->commit();
        return ['code' => 200, 'msg' => ''];
    }

}
